/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package controllers

import (
	"encoding/json"
	"net/http"
	"prim-server/common"
	"prim-server/errcode"
	"prim-server/logger"
	"prim-server/util"

	"github.com/astaxie/beego"
	"github.com/pkg/errors"
)

const (
	SuccessCode = "0"
	FailedCode  = "1"
	SuccessMsg  = "success"
	FailedMsg   = "failed"
)

type CommonController struct {
	beego.Controller
}
type Response struct {
	Code string      `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

// HandleBusinessErr is a function
func (ctrl *CommonController) HandleErrCode(errcode errcode.Status) {
	ctrl.Ctx.ResponseWriter.WriteHeader(int(errcode.Code))
	data := &Response{errcode.ErrorCode, errcode.Message, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleErrCode MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

// HandleBusinessObj is a function
func (ctrl *CommonController) HandleBusinessObj(obj interface{}) {
	ctrl.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
	data := &Response{SuccessCode, SuccessMsg, obj}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleStandObj MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

func (ctrl *CommonController) HandleBusinessSuccess() {
	ctrl.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
	data := &Response{SuccessCode, SuccessMsg, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleStandObj MarshalIndent error: %v", err)
	}
	ctrl.Ctx.ResponseWriter.Write(res)
}

// CheckUserIdFromSession 检查session内id和传入id是否一致
func (ctrl *CommonController) CheckUserIdFromSession(userId string) error {
	userInfo := ctrl.GetSession(common.SessionUserId)
	if userInfo == nil {
		err := errors.Errorf("Failed to get userId from session id")
		logger.Error(err.Error())
		return err
	}
	userIdInSession := userInfo
	if userIdInSession != userId {
		err := errors.Errorf("Failed to get userId from session id")
		logger.Error(err.Error())
		return err
	}
	return nil
}

func (ctrl *CommonController) GetUserIdFromToken() (string, error) {
	token := ctrl.Ctx.Request.Header.Get("token")
	if len(token) == 0 {
		token = ctrl.Ctx.GetCookie("token")
	}
	if len(token) == 0 {
		token = ctrl.Ctx.Input.Query("token")
	}
	if len(token) == 0 {
		return "", errors.Errorf("Failed to get token")
	}
	claims, err := util.ParseToken(token)
	if err != nil {
		logger.Error(err.Error())
		return "", errors.Errorf("Failed to get token")
	}
	return claims.Id, nil
}

func (ctrl *CommonController) BuildSuccessResponse() []byte {
	data := &Response{SuccessCode, SuccessMsg, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("BuildSuccessResponse MarshalIndent error: %v", err)
	}
	return res
}
func (ctrl *CommonController) BuildFailResponse(errcode errcode.Status) []byte {
	data := &Response{FailedCode, errcode.Message, nil}
	res, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		logger.Error("HandleErrCode MarshalIndent error: %v", err)
	}
	return res
}
